#  网络通信
import json
import base64
import time

import requests
import motorfuntion as motor
from threading import Thread

img_path = "/home/pi/Downloads/bottle/test/j.jpg"

l = 320
w = 480

def my_bd():
    t = Thread(target=baidujianche)
    t.start()

def my_jc():
    t1 = Thread(target=jianchekaishi)
    t1.start()

#  检测函数
def baidujianche():
    # 目标图片的 本地文件路径，支持jpg/png/bmp格式
    IMAGE_FILEPATH = img_path

    # 可选的请求参数
    # threshold: 默认值为建议阈值，请在 我的模型-模型效果-完整评估结果-详细评估 查看建议阈值
    PARAMS = {"threshold": 0.7}

    # 服务详情 中的 接口地址
    # MODEL_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/lajijian"
    #  水面垃圾检测 水面混合
    MODEL_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/jwyyds"

    # 调用 API 需要 ACCESS_TOKEN。若已有 ACCESS_TOKEN 则于下方填入该字符串
    # 否则，留空 ACCESS_TOKEN，于下方填入 该模型部署的 API_KEY 以及 SECRET_KEY，会自动申请并显示新 ACCESS_TOKEN
    ACCESS_TOKEN = ""
    API_KEY = "feKQfSWaQnbFK1jftYyND3RO"
    SECRET_KEY = "EYD7HF3YTefLfy1TT5jNaiGWPuXK876U"

    print("1. 读取目标图片 '{}'".format(IMAGE_FILEPATH))
    with open(IMAGE_FILEPATH, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        base64_str = base64_data.decode('UTF8')
    print("将 BASE64 编码后图片的字符串填入 PARAMS 的 'image' 字段")
    PARAMS["image"] = base64_str

    if not ACCESS_TOKEN:
        # print("2. ACCESS_TOKEN 为空，调用鉴权接口获取TOKEN")
        auth_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials""&client_id={}&client_secret={}".format(
            API_KEY, SECRET_KEY)
        auth_resp = requests.get(auth_url)
        auth_resp_json = auth_resp.json()
        ACCESS_TOKEN = auth_resp_json["access_token"]
        # print("新 ACCESS_TOKEN: {}".format(ACCESS_TOKEN))
    else:
        print("2. 使用已有 ACCESS_TOKEN")

    # print("3. 向模型接口 'MODEL_API_URL' 发送请求")
    request_url = "{}?access_token={}".format(MODEL_API_URL, ACCESS_TOKEN)
    response = requests.post(url=request_url, json=PARAMS)
    response_json = response.json()
    response_str = json.dumps(response_json, indent=4, ensure_ascii=False)
    print("检测结果", response_str)

def baidujianche1():
    # 目标图片的 本地文件路径，支持jpg/png/bmp格式
    IMAGE_FILEPATH = img_path

    # 可选的请求参数
    # threshold: 默认值为建议阈值，请在 我的模型-模型效果-完整评估结果-详细评估 查看建议阈值
    PARAMS = {"threshold": 0.7}

    # 服务详情 中的 接口地址
    # MODEL_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/lajijian"
    #  水面垃圾检测 水面混合
    MODEL_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/jwyyds"

    # 调用 API 需要 ACCESS_TOKEN。若已有 ACCESS_TOKEN 则于下方填入该字符串
    # 否则，留空 ACCESS_TOKEN，于下方填入 该模型部署的 API_KEY 以及 SECRET_KEY，会自动申请并显示新 ACCESS_TOKEN
    ACCESS_TOKEN = ""
    API_KEY = "feKQfSWaQnbFK1jftYyND3RO"
    SECRET_KEY = "EYD7HF3YTefLfy1TT5jNaiGWPuXK876U"

    # print("1. 读取目标图片 '{}'".format(IMAGE_FILEPATH))
    with open(IMAGE_FILEPATH, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        base64_str = base64_data.decode('UTF8')
    # print("将 BASE64 编码后图片的字符串填入 PARAMS 的 'image' 字段")
    PARAMS["image"] = base64_str

    if not ACCESS_TOKEN:
        # print("2. ACCESS_TOKEN 为空，调用鉴权接口获取TOKEN")
        auth_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials""&client_id={}&client_secret={}".format(
            API_KEY, SECRET_KEY)
        auth_resp = requests.get(auth_url)
        auth_resp_json = auth_resp.json()
        ACCESS_TOKEN = auth_resp_json["access_token"]
        # print("新 ACCESS_TOKEN: {}".format(ACCESS_TOKEN))
    else:
        print("2. 使用已有 ACCESS_TOKEN")

    # print("3. 向模型接口 'MODEL_API_URL' 发送请求")
    request_url = "{}?access_token={}".format(MODEL_API_URL, ACCESS_TOKEN)
    response = requests.post(url=request_url, json=PARAMS)
    response_json = response.json()
    response_str = json.dumps(response_json, indent=4, ensure_ascii=False)
    # print("检测结果", response_str)
    user_dict = json.loads(response_str)
    b_results = list(user_dict['results'])
    c_location = dict(b_results[0])
    d_point = dict(c_location['location'])
    return d_point

def jianchebreak():
    print("停止检测")
    print("停止自动检测")

#  开始检测 自动收集垃圾
def jianchekaishi():
    a = baidujianche1()
    height = a["height"]
    left = a['left']
    top = a['top']
    width = a['width']
    b=1
    while b>0:
        if l - ((left +  width) / 2) < 0:
            motor.my_left()
            motor.my_forwod_litle()
            a = baidujianche1()
            height = a["height"]
            left = a['left']
            top = a['top']
            width = a['width']
            time.sleep(2)
            if l - ((left +  width) / 2) < 0:
                motor.my_left()
                motor.my_forwod_litle()
                time.sleep(2)
            elif l - ((left +  width) / 2) > 0:
                motor.my_right()
                motor.my_forwod_litle()
                time.sleep(2)
            else:
                motor.my_forwod_litle()
                time.sleep(2)
            b=-1
            break
        elif l - ((left +  width) / 2) > 0:
            motor.my_right()
            motor.my_forwod_litle()
            a = baidujianche1()
            height = a["height"]
            left = a['left']
            top = a['top']
            width = a['width']
            time.sleep(2)
            if l - ((left + width) / 2) < 0:
                motor.my_left()
                motor.my_forwod_litle()
                time.sleep(2)
            elif l - ((left + width) / 2) > 0:
                motor.my_right()
                motor.my_forwod_litle()
                time.sleep(2)
            else:
                motor.my_forwod_litle()
                time.sleep(2)
            b=-1
            break
        else:
            motor.my_forwod_litle()
            b=-1
            time.sleep(2)
    time.sleep(0.2)
    motor.my_forwod()
    print("自动拾取结束")



